/**
 * 
 */
package com.csair.youth.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.mail.MessagingException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.mail.EmailException;
import org.apache.log4j.Logger;

import com.csair.youth.constant.Constant;
import com.csair.youth.constant.ResourceConstant;
import com.csair.youth.dao.impl.hibernate3.PermissionDaoImpl;
import com.csair.youth.dao.impl.hibernate3.ResourceDaoImpl;
import com.csair.youth.dao.impl.hibernate3.RoleDaoImpl;
import com.csair.youth.dao.impl.hibernate3.RolePermissionDaoImpl;
import com.csair.youth.dao.impl.hibernate3.UserDaoImpl;
import com.csair.youth.database.Permission;
import com.csair.youth.database.Resource;
import com.csair.youth.database.RolePermission;
import com.csair.youth.database.User;

/**
 * @author mickey
 *
 */
public class ResourceServiceImpl {
	private static final Logger log = Logger.getLogger(ResourceServiceImpl.class);
	
	private ResourceDaoImpl dao;
	private PermissionDaoImpl pdao;
	private RolePermissionDaoImpl rpdao;
	private RoleDaoImpl rdao;
	private UserDaoImpl udao;
	private EmailServiceImpl emailService;
	
	public ResourceDaoImpl getDao() {
		return dao;
	}

	public void setDao(ResourceDaoImpl dao) {
		this.dao = dao;
	}

	public PermissionDaoImpl getPdao() {
		return pdao;
	}

	public void setPdao(PermissionDaoImpl pdao) {
		this.pdao = pdao;
	}

	public RolePermissionDaoImpl getRpdao() {
		return rpdao;
	}

	public void setRpdao(RolePermissionDaoImpl rpdao) {
		this.rpdao = rpdao;
	}

	public RoleDaoImpl getRdao() {
		return rdao;
	}

	public void setRdao(RoleDaoImpl rdao) {
		this.rdao = rdao;
	}

	public UserDaoImpl getUdao() {
		return udao;
	}

	public void setUdao(UserDaoImpl udao) {
		this.udao = udao;
	}

	public EmailServiceImpl getEmailService() {
		return emailService;
	}

	public void setEmailService(EmailServiceImpl emailService) {
		this.emailService = emailService;
	}

	public void copyFile(File f, String path) throws IOException{
		FileUtils.copyFile(f, new File(path));
	}
	
	public File getTmpPath(){
		String path = ResourceConstant.getInstance().getUploadTmpPath();
		File dir = new File(path);
		if(!dir.exists()){
			boolean suc = dir.mkdirs();
			if(!suc) return null;
		}
		return dir;
	}
	
	public void saveResource(Resource item){
		if(item == null) return;
		if(StringUtils.isEmpty(item.getId())) item.setId(null);
		dao.saveOrUpdate(item);
	}
	
	public Resource getResource(String id){
		return dao.findById(id);
	}
	
	public Resource getResourceWithUser(String id){
		return dao.getResourceWithUser(id);
	}
	
	public Resource getResourceByPath(String path){
		return dao.getResourceByPath(path);
	}
	
	public boolean deleteResourceById(String id){
		//删除数据库记录前需要先删除物理文件
		Resource res = getResource(id);
		if(res != null){
			String path = res.getAbsolutePath();
			File f = new File(path);
			boolean suc = f.delete();
			if(!suc){
				log.error("物理文件删除失败:"+path);
				return false;
			}
			else{
				dao.deleteById(id);
				return true;
			}
		}
		log.error("Resource为空，无法删除");
		return false;
	}
	
	public void notifyAuditorsByEmail(Resource item, String auditUrl){
		Permission p = pdao.findFirstPermissionByURL(Constant.PERMISSION_AUDIT_EMAIL_URL);
		if(p != null){
			List rps = rpdao.findByPermissionId(p.getId());
			if(rps == null || rps.size() == 0){
				log.error("url为"+Constant.PERMISSION_AUDIT_EMAIL_URL+"的权限没有对应角色，将不发送email!");
				return;
			}
			else{
				String roleIds[] = new String[rps.size()];
				int count = 0;
				Iterator iter = rps.iterator();
				while(iter.hasNext()){
					RolePermission rp = (RolePermission)iter.next();
					roleIds[count++] = rp.getRoleId();
				}
				List users = udao.getUsersInRoles(roleIds);
				if(users == null || users.size() == 0){
					log.error("url为"+Constant.PERMISSION_AUDIT_EMAIL_URL+"的权限没有对应用户，将不发送email!");
				}
				else{
					//真正发送email了
					String title = "青年资源库有新资源待审核";
					for(int i=0; i<users.size(); i++){
						User u = (User)users.get(i);
						StringBuffer sb = new StringBuffer();
						sb.append("尊敬的"+u.getName()+",您好!\n  青年资源库有新资源待审核，请点击以下链接进行审核:\n");
						sb.append("  "+auditUrl+"?p="+item.getId()+"\n");
						try {
							emailService.sendMail(u, title, sb.toString());
						} catch (EmailException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							log.error("发送邮件发生错误，user="+u.getEmail(), e);
						} catch (MessagingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							log.error("发送邮件发生错误，user="+u.getEmail(), e);
						}
					}
				}
			}
		}
		else{
			log.error("没有找到url为"+Constant.PERMISSION_AUDIT_EMAIL_URL+"的权限，将不发送email!");
			return;
		}
	}
	
	public List<Resource> getLatestResources(int count){
		return dao.getLatestResources(count);
	}
	
	public List<Resource> getHottestResources(int count){
		return dao.getHottestResources(count);
	}
}
